﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net;
using System.IO;
using System.Text;
using System.Xml;
using System.Text.RegularExpressions;
using System.Windows.Forms;

namespace Javavaj.iHunter.ThuLearnChannels
{
    /*internal*/public partial class ConfigDialog : Form
    {
        private class CourseInfo
        {
            private string courseId;
            private string courseName;
            
            public CourseInfo(string id, string name)
            {
                this.courseId = id;
                this.courseName = name;
            }

            public string CourseId
            {
                get { return courseId; }
                set { courseId = value; }
            }
            public string CourseName
            {
                get { return courseName; }
                set { courseName = value; }
            }
        }

        private XmlDocument oldsettings;
        private XmlDocument newsettings;

        private void SetDialogBySettings(XmlDocument settings)
        {
            try
            {
                if (settings != null)
                {
                    textBoxUsername.Text = settings.DocumentElement["Username"].InnerText;
                    maskedTextBoxPassword.Text = settings.DocumentElement["Password"].InnerText;
                    checkedListBoxCourse.Items.Clear();
                    foreach (XmlElement ele in settings.DocumentElement.SelectNodes("Course"))
                    {
                        checkedListBoxCourse.Items.Add(new CourseInfo(ele["Id"].InnerText, ele["Title"].InnerText), bool.Parse(ele["Chosen"].InnerText));
                    }
                }
            }
            catch
            {
                textBoxUsername.Text = "";
                maskedTextBoxPassword.Text = "";
                checkedListBoxCourse.Items.Clear();
            }
        }

        private XmlDocument MakeSettingsByDialog()
        {
            XmlDocument settings = new XmlDocument();
            settings.LoadXml("<Settings><Username/><Password/></Settings>");
            settings.DocumentElement["Username"].InnerText = textBoxUsername.Text;
            settings.DocumentElement["Password"].InnerText = maskedTextBoxPassword.Text;

            for(int i = 0; i<checkedListBoxCourse.Items.Count; i++)
            {
                XmlElement node = settings.CreateElement("Course");
                node.InnerXml = "<Chosen>"+checkedListBoxCourse.GetItemChecked(i).ToString()+"</Chosen>"
                    +"<Id>"+((CourseInfo)checkedListBoxCourse.Items[i]).CourseId+"</Id>"
                    +"<Title>"+ ((CourseInfo)checkedListBoxCourse.Items[i]).CourseName+ "</Title>";
                settings.DocumentElement.AppendChild(node);
                
            }
            return settings;
        }

        public ConfigDialog(XmlDocument settings)
        {
            InitializeComponent();
            oldsettings = settings;
            SetDialogBySettings(oldsettings);
            checkedListBoxCourse.DisplayMember = "CourseName";
        }

        public XmlDocument NewSettings
        {
            get { return newsettings; }
        }

        private void buttonLogin_Click(object sender, EventArgs e)
        {
            this.Cursor = Cursors.WaitCursor;
            
            byte[] data = Encoding.UTF8.GetBytes("userid=" + textBoxUsername.Text + "&userpass=" + maskedTextBoxPassword.Text + "&submit1=%B5%C7%C2%BC");

            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(@"http://learn.tsinghua.edu.cn/use_go.jsp");
            request.Method = "POST";
            request.Accept = @"image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/x-shockwave-flash, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, */*";
            request.ContentType = @"application/x-www-form-urlencoded";
            request.ContentLength = data.Length;

            CookieContainer cookies = new CookieContainer();
            request.CookieContainer = cookies;

            Stream reqStream = null;
            HttpWebResponse response = null;
            StreamReader reader = null;
            string responseContent = null;

            try
            {
                reqStream = request.GetRequestStream();
                reqStream.Write(data, 0, data.Length);
                reqStream.Close();

                response = (HttpWebResponse)request.GetResponse();
                reader = new StreamReader(response.GetResponseStream(), Encoding.Default);
                responseContent = reader.ReadToEnd();

                reader.Close();
                response.Close();

                //检查是否登录成功
                if (!responseContent.Contains("/lesson/teacher/main.jsp"))
                    throw new Exception();

                //获得各个课程的信息对应的课程信息
                request = (HttpWebRequest)WebRequest.Create(@"http://learn.tsinghua.edu.cn/lesson/student/MyCourse.jsp");
                request.CookieContainer = cookies;

                response = (HttpWebResponse)request.GetResponse();
                reader = new StreamReader(response.GetResponseStream(), Encoding.Default);
                responseContent = reader.ReadToEnd();

                Regex r = new Regex(@"course_id=(?<Id>\d*)[^>]*>\s*(?<Title>[^(]*)", RegexOptions.Compiled | RegexOptions.IgnoreCase);
                MatchCollection matches = r.Matches(responseContent);

                checkedListBoxCourse.Items.Clear();
                foreach (Match m in matches)
                {
                    checkedListBoxCourse.Items.Add(new CourseInfo(m.Groups["Id"].Value, m.Groups["Title"].Value), true);
                }

                reader.Close();
                response.Close();
            }
            catch
            {
                if (reader != null)
                    reader.Close();
                if (response != null)
                    response.Close();
                MessageBox.Show("无法获得课程列表！请检查用户名、密码以及网络连接是否正确。");
                SetDialogBySettings(oldsettings);
            }
            finally
            {
                this.Cursor = Cursors.Default;
            }
        }

        private void buttonOk_Click(object sender, EventArgs e)
        {
            if (this.checkedListBoxCourse.Items.Count != 0)
                newsettings = MakeSettingsByDialog();
            else
                newsettings = null;
        }

        private void textBoxUsername_TextChanged(object sender, EventArgs e)
        {
            if (checkedListBoxCourse.Items.Count != 0)
                checkedListBoxCourse.Items.Clear();
            maskedTextBoxPassword.Text = "";
        }

        private void maskedTextBoxPassword_TextChanged(object sender, EventArgs e)
        {
            if (checkedListBoxCourse.Items.Count != 0)
                checkedListBoxCourse.Items.Clear();
        }
    }
}
